package org.desktop.web.server;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.text.StrSubstitutor;
import org.desktop.web.client.emails.EmailService;
import org.desktop.web.server.locator.ServiceLocator;
import org.desktop.web.server.locator.ServiceLocator.ServiceName;
import org.desktop.web.server.util.RpcUtil;
import org.desktop.web.shared.domain.entities.Email;

import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;

public class EmailServiceImpl extends AbstractPagingService<Email> implements
		EmailService {

	private String urlByUser = RpcUtil.createUrlService(ServiceLocator.find(ServiceName.TIMESHEET_SERVICE),"emailses/user/${idUser}");
	
	private String emailBasUrl = RpcUtil.createUrlService(ServiceLocator.find(ServiceName.TIMESHEET_SERVICE),"emailses");
	@Override
	public PagingLoadResult<Email> getEmailByUser(final int idUser,
			Map<String, String> headers, PagingLoadConfig loadConfig)
			throws Exception {
		// TODO Auto-generated method stub
		
		return getDatas(headers,loadConfig,new StrSubstitutor(new HashMap<String, String>(){
			{
				put("idUser",Integer.toString(idUser));
			}
		}).replace(urlByUser));
	}

	@Override
	public Class<?> getType() {
		// TODO Auto-generated method stub
		return Email.class;
	}

	@Override
	public boolean delete(Map<String, String> headers, Email email) throws Exception {
		HttpURLConnection con = RpcUtil.getRESTConnection(new URL(emailBasUrl+"/"+email.getIdEmail()), "DELETE", headers);
		InputStream in = con.getInputStream();
		int code = con.getResponseCode();
		
		in.close();
		return code==200;
	}

	
}
